package com.ihome.android.market2.asynctask;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.ihome.android.EAApp;
import com.ihome.android.analytic.JsonAnalytic;
import com.ihome.android.http.HttpActions;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.academy.R;
import com.ihome.android.academy.service.GetMarketInfoService;
import com.ihome.android.academy.service.GetMarketInfoSynObj;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.MyProgressDialog;
import com.ihome.android.market2.view.DialogFactory.onBtnClickListener;
import com.ihome.android.mod.LoginMod;
import com.ihome.android.util.Util;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

/**
 * 应用商城用户注册
 * 
 * @author Emerson
 * 
 */
public class UserRegisterTask extends AsyncTask<Bundle, Integer, Bundle> {
	private final String		TAG	= UserRegisterTask.class.getSimpleName();
	private Context				context;
	private MyProgressDialog	progressDialog;

	public UserRegisterTask(Context context) {
		this.context = context;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		
		if(!(context instanceof Activity) )
			return;
		progressDialog = MyProgressDialog.getDialog(context, context.getString(R.string.user_grabing_data));
		progressDialog.show();
		progressDialog.setCancelable(true);
		progressDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				if (UserRegisterTask.this.getStatus().compareTo(AsyncTask.Status.FINISHED) != 0)
					UserRegisterTask.this.cancel(true);
			}
		});
	}

	@Override
	protected Bundle doInBackground(Bundle... params) {
		Bundle b = params[0];
		String appUserName = b.getString(HttpKeys.KEY_APPUSERNAME);
		String loginPwd = b.getString(HttpKeys.KEY_PAYPASSWORD);
		
		LogUtil.v(TAG, "appUserName = " + appUserName);

		if (TextUtils.isEmpty(appUserName)) {
			String[] msg = {"","","","","user.register",""};
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg);
			return null;
		}

		try {

			// String result = Util.getTestDataFromAssets(context,
			// "common_success.json");
			String result = new HttpActions(context).register(appUserName, loginPwd);
			LogUtil.v(TAG, "result = " + result);
			if (!TextUtils.isEmpty(result)) {
				JsonAnalytic.getInstance().analyseSimpleResult(result);
			}
			else {
				String[] msg = {"","","","","user.register",""};
				UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg);
				cancel(true);
			}
		} catch (ITVException e) {
			String[] msg = {"","","","","user.register",""};
			UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg);
			e.printStackTrace();
			LogUtil.e(TAG, e.toString());
			b.putInt(HttpKeys.KEY_CODE, e.getStatusCode());
			b.putString(HttpKeys.KEY_DESCRIPTION, e.getMessage());
		}
		
		
		if(!b.containsKey(HttpKeys.KEY_CODE)) {
			try {
				Util.saveOTTUserName(context, b.getString(HttpKeys.KEY_APPUSERNAME));
				Util.saveUserPwd(context, Util.MD5Encode(b.getString(HttpKeys.KEY_PAYPASSWORD)));
			} catch (ITVException e) {
				String[] msg = {"","","","","user.register",""};
				UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg);
				e.printStackTrace();
			}
		}
		
		return b;
	}

	@Override
	protected void onPostExecute(Bundle result) {
		super.onPostExecute(result);
		if (progressDialog != null)
			progressDialog.dismiss();

		/** 请求出错处理 */
		if (result.containsKey(HttpKeys.KEY_CODE)) {
			
			if(context instanceof GetMarketInfoService) {
				LogUtil.v(TAG,"------ GetMarketInfoService --> Failure" );
				new Thread() {
					public void run() {
						synchronized (GetMarketInfoSynObj.getInstance()) {
							// 处理完成，唤醒等待的同步对象
							GetMarketInfoSynObj.getInstance().notifyAll();
						}
					};
				}.start();
			}else{
				String[] msg = {"","","","","user.register",""};
				UserBehaviorLog.getInstance().writeLog(UserBehavior.STORERUN_EXCEPTION, NotifyType.TYPE_FAILURE, "", msg);
				if(ITVException.CODE_LOGINOUT_THREE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGINOUT_ONE == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_SESSIONKEY == result.getInt(HttpKeys.KEY_CODE)||ITVException.CODE_LOGIN_ONE == result.getInt(HttpKeys.KEY_CODE)){
					new DialogFactory(context).showDialog("",result.getString(HttpKeys.KEY_DESCRIPTION) + "(" + result.getInt(HttpKeys.KEY_CODE) + ")",context.getString(R.string.dialog_ok),new onBtnClickListener() {
						
						@Override
						public void btnRightClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void btnNeutralClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
						
						@Override
						public void btnLeftClickListener(View v) {
							// TODO Auto-generated method stub
							EAApp.getApp().exitApp(true);
						}
						
						@Override
						public void btnCloseClickListener(View v) {
							// TODO Auto-generated method stub
							
						}
					});
					return;
				}
				new DialogFactory(context).showDialog(result.getString(HttpKeys.KEY_DESCRIPTION) + "("
						+ result.getInt(HttpKeys.KEY_CODE) + ")");
			}
			
			
			return;
		}
		
		
//		else if(context instanceof InitialActivity){
			LoginMod.autoLogin(context);
//		}
		

	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		LogUtil.i(TAG, "--> onCancelled");
		if (progressDialog != null)
			progressDialog.dismiss();

	}

}
